<template>
  <div class="file-list">
    <el-card class="file-card">
      <template #header>
        <div class="card-header">
          <span>文件管理</span>
          <div class="header-actions">
            <el-select
              v-model="searchForm.category"
              placeholder="文件分类"
              clearable
              style="width: 150px; margin-right: 10px"
              @change="handleSearch"
            >
              <el-option label="全部分类" value="" />
              <el-option label="头像" value="AVATAR" />
              <el-option label="证书" value="CERTIFICATE" />
              <el-option label="训练照片" value="TRAINING" />
              <el-option label="课程" value="COURSE" />
              <el-option label="公告" value="ANNOUNCEMENT" />
              <el-option label="其他" value="OTHER" />
            </el-select>
            <el-select
              v-model="searchForm.fileType"
              placeholder="文件类型"
              clearable
              style="width: 150px; margin-right: 10px"
              @change="handleSearch"
            >
              <el-option label="全部类型" value="" />
              <el-option label="图片" value="image" />
              <el-option label="视频" value="video" />
              <el-option label="文档" value="document" />
            </el-select>
            <el-input
              v-model="searchForm.keyword"
              placeholder="文件名/原始文件名"
              style="width: 300px; margin-right: 10px"
              clearable
              @clear="handleSearch"
              @keydown.enter="handleSearch"
            >
              <template #append>
                <el-button icon="Search" @click="handleSearch" :loading="loading" />
              </template>
            </el-input>
            <el-button type="primary" @click="handleRefresh">刷新</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="fileList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="文件预览" width="120">
          <template #default="scope">
            <div class="file-preview">
              <el-image
                v-if="scope.row.fileType === 'image'"
                :src="scope.row.fileUrl"
                :preview-src-list="[scope.row.fileUrl]"
                fit="cover"
                class="preview-image"
              />
              <div v-else class="file-icon">
                <el-icon v-if="scope.row.fileType === 'video'">
                  <VideoPlay />
                </el-icon>
                <el-icon v-else>
                  <Document />
                </el-icon>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="originalName" label="原始文件名" show-overflow-tooltip>
          <template #default="scope">
            <a :href="scope.row.fileUrl" target="_blank" class="file-link">
              {{ scope.row.originalName }}
            </a>
          </template>
        </el-table-column>
        <el-table-column prop="fileType" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getFileTypeTagType(scope.row.fileType)">
              {{ formatFileType(scope.row.fileType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120">
          <template #default="scope">
            <el-tag :type="getCategoryTagType(scope.row.category)">
              {{ formatCategory(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="fileSize" label="大小" width="120">
          <template #default="scope">
            {{ formatFileSize(scope.row.fileSize) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="上传时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-actions">
        <el-button
          type="danger"
          :disabled="selectedFiles.length === 0"
          @click="handleBatchDelete"
        >
          批量删除 ({{ selectedFiles.length }})
        </el-button>
      </div>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 文件详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="文件详情"
      width="800px"
    >
      <div class="file-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="文件ID">{{ currentFile.id }}</el-descriptions-item>
          <el-descriptions-item label="原始文件名">{{ currentFile.originalName }}</el-descriptions-item>
          <el-descriptions-item label="文件名">{{ currentFile.fileName }}</el-descriptions-item>
          <el-descriptions-item label="文件类型">
            <el-tag :type="getFileTypeTagType(currentFile.fileType)">
              {{ formatFileType(currentFile.fileType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="文件分类">
            <el-tag :type="getCategoryTagType(currentFile.category)">
              {{ formatCategory(currentFile.category) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="文件大小">{{ formatFileSize(currentFile.fileSize) }}</el-descriptions-item>
          <el-descriptions-item label="MIME类型">{{ currentFile.mimeType }}</el-descriptions-item>
          <el-descriptions-item label="存储类型">{{ currentFile.storageType }}</el-descriptions-item>
          <el-descriptions-item label="是否公开">
            <el-tag :type="currentFile.isPublic ? 'success' : 'info'">
              {{ currentFile.isPublic ? '是' : '否' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="上传时间">{{ currentFile.createdAt }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ currentFile.updatedAt }}</el-descriptions-item>
          <el-descriptions-item label="访问URL" :span="2">
            <el-link :href="currentFile.fileUrl" target="_blank" type="primary">
              {{ currentFile.fileUrl }}
            </el-link>
          </el-descriptions-item>
        </el-descriptions>

        <div class="file-preview-large" v-if="currentFile.fileType === 'image'">
          <el-image
            :src="currentFile.fileUrl"
            :preview-src-list="[currentFile.fileUrl]"
            fit="contain"
            style="width: 100%; height: 400px"
          />
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleDownload(currentFile)">下载</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FileInfo } from '@/types/api/file'
import { fileApi } from '@/api/modules/file'
import type { FileListResponse } from '@/types/api/file'
import { formUtils } from '@/utils'

// 表格相关
const loading = ref(false)
const fileList = ref<FileInfo[]>([])
const currentFile = ref<FileInfo>({
  id: 0,
  fileName: '',
  originalName: '',
  filePath: '',
  fileUrl: '',
  fileType: 'image',
  mimeType: '',
  fileSize: 0,
  storageType: 'LOCAL',
  category: 'OTHER',
  uploaderId: 0,
  isPublic: true,
  createdAt: '',
  updatedAt: ''
})

// 搜索表单
const searchForm = reactive({
  category: '',
  fileType: '',
  keyword: ''
})

// 分页相关
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const detailDialogVisible = ref(false)

// 选中的文件
const selectedFiles = ref<FileInfo[]>([])

// 获取文件列表
const getFileList = async () => {
  try {
    loading.value = true
    const response = await fileApi.getFileList({
      category: searchForm.category as any,
      fileType: searchForm.fileType as any,
      page: pagination.page,
      pageSize: pagination.pageSize
    })
    fileList.value = response.data.data.list
    pagination.total = response.data.data.total
  } catch (error) {
    ElMessage.error('获取文件列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getFileList()
}

// 刷新列表
const handleRefresh = () => {
  getFileList()
}

// 查看文件详情
const handleView = (row: FileInfo) => {
  currentFile.value = row
  detailDialogVisible.value = true
}

// 删除文件
const handleDelete = async (row: FileInfo) => {
  formUtils.handleDeleteConfirm(`文件 "${row.originalName}"`, async () => {
    await fileApi.deleteFile(row.id)
    getFileList()
  }, {
    successMessage: '删除成功',
    errorMessage: '删除失败'
  })
}

// 批量删除文件
const handleBatchDelete = async () => {
  if (selectedFiles.value.length === 0) {
    ElMessage.warning('请至少选择一个文件')
    return
  }

  formUtils.handleBatchDeleteConfirm(
    selectedFiles.value.length,
    '文件',
    async () => {
      // 批量删除
      for (const file of selectedFiles.value) {
        await fileApi.deleteFile(file.id)
      }
      selectedFiles.value = []
      getFileList()
    },
    {
      successMessage: '批量删除成功',
      errorMessage: '批量删除失败'
    }
  )
}

// 下载文件
const handleDownload = (row: FileInfo) => {
  // 创建一个隐藏的a标签来下载文件
  const link = document.createElement('a')
  link.href = row.fileUrl
  link.download = row.originalName
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 处理选中变化
const handleSelectionChange = (selection: FileInfo[]) => {
  selectedFiles.value = selection
}

// 分页相关方法
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  getFileList()
}

const handleCurrentChange = (val: number) => {
  pagination.page = val
  getFileList()
}

// 格式化文件类型
const formatFileType = (type: string) => {
  const typeMap: Record<string, string> = {
    'image': '图片',
    'video': '视频',
    'document': '文档'
  }
  return typeMap[type] || type
}

// 获取文件类型标签类型
const getFileTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    'image': 'primary',
    'video': 'danger',
    'document': 'success'
  }
  return typeMap[type] || 'info'
}

// 格式化分类
const formatCategory = (category: string) => {
  const categoryMap: Record<string, string> = {
    'AVATAR': '头像',
    'CERTIFICATE': '证书',
    'TRAINING': '训练照片',
    'COURSE': '课程',
    'ANNOUNCEMENT': '公告',
    'OTHER': '其他'
  }
  return categoryMap[category] || category
}

// 获取分类标签类型
const getCategoryTagType = (category: string) => {
  const categoryMap: Record<string, string> = {
    'AVATAR': '',
    'CERTIFICATE': 'warning',
    'TRAINING': 'success',
    'COURSE': 'primary',
    'ANNOUNCEMENT': 'danger',
    'OTHER': 'info'
  }
  return categoryMap[category] || 'info'
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB'
  } else if (size < 1024 * 1024 * 1024) {
    return (size / (1024 * 1024)).toFixed(2) + ' MB'
  } else {
    return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
  }
}

// 生命周期
onMounted(() => {
  getFileList()
})
</script>

<style scoped>
.file-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-actions {
  margin: 20px 0;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.file-preview {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.file-icon {
  font-size: 32px;
  color: #909399;
}

.file-link {
  color: var(--el-color-primary);
  text-decoration: none;
}

.file-link:hover {
  text-decoration: underline;
}

.file-detail {
  margin-bottom: 20px;
}

.file-preview-large {
  margin-top: 20px;
  text-align: center;
}
</style>
